<template>
  <div class="four">
    <el-row :gutter="10" class="mb8 grid-content" v-if="false"> </el-row>
    <div class="title">
      {{ this.templateId ? "修改附加模板" : "新建附加模板" }}
    </div>
    <div class="form-content">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        class="editor-plus-form"
        size="small"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="附加列表模板名称：" prop="name">
              <!-- <el-input v-model="ruleForm.name" @blur='nameRepeat'></el-input> -->
              <el-input
                v-model="ruleForm.name"
                maxlength="20"
                style="width: calc(100% - 130px)"
                show-word-limit
              >
                <!-- <template slot="append">0-20</template> -->
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="内容最大字数：" prop="countPerRow">
              <el-input
                v-model.number="ruleForm.countPerRow"
                maxlength="4"
                @input="
                  (val) => {
                    ruleForm.countPerRow = val.replace(/\D/g, '');
                  }
                "
                @blur="
                  () => (ruleForm.countPerRow = ruleForm.countPerRow || 30)
                "
              >
                <template slot="append">0-9999</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标题最大长度：" prop="maxHeader">
              <el-input
                v-model.number="ruleForm.maxHeader"
                maxlength="2"
                @input="
                  (val) => {
                    ruleForm.maxHeader = val.replace(/\D/g, '');
                  }
                "
                @blur="() => (ruleForm.maxHeader = ruleForm.maxHeader || 30)"
              >
                <template slot="append">0-99</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题图片大小：" prop="imgSize">
              <!-- <el-input v-model="ruleForm.imgSize"></el-input> -->
              <el-input
                v-model.number="ruleForm.imgSize1"
                maxlength="4"
                style="width: 50%"
                @input="
                  (val) => {
                    ruleForm.imgSize1 = val.replace(/\D/g, '');
                  }
                "
                @blur="() => (ruleForm.imgSize1 = ruleForm.imgSize1 || 320)"
              >
                <template slot="prepend">宽</template>
              </el-input>

              <el-input
                v-model.number="ruleForm.imgSize2"
                maxlength="4"
                style="width: 50%"
                @input="
                  (val) => {
                    ruleForm.imgSize2 = val.replace(/\D/g, '');
                  }
                "
                @blur="() => (ruleForm.imgSize2 = ruleForm.imgSize2 || 240)"
              >
                <template slot="prepend">高</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片对齐方式：" prop="imgAlign">
              <el-radio-group v-model="ruleForm.imgAlign">
                <el-radio label="0">宽度对齐</el-radio>
                <el-radio label="1">高度对齐 </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="文章列表区高度：" prop="articlePageHeight">
              <el-input-number
                v-model.number="ruleForm.articlePageHeight"
                :min="0"
                :max="999"
                @blur="
                  () =>
                    (ruleForm.articlePageHeight =
                      ruleForm.articlePageHeight || 380)
                "
              >
              </el-input-number>
              <span>(0-999)</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章标新期限：" prop="articleForNew">
              <el-input-number
                v-model.number="ruleForm.articleForNew"
                :min="0"
                :max="99"
              ></el-input-number>
              <span>(天0-99)</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="每行文章数目：" prop="oneRowArticleNum">
              <el-input-number
                v-model.number="ruleForm.oneRowArticleNum"
                :min="1"
                :max="6"
              ></el-input-number>
              <span>(篇:1-6)</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文章排序方式：" prop="listOrder">
              <el-radio-group v-model="ruleForm.listOrder">
                <el-radio label="createdDate desc">发布时间降序 </el-radio>
                <el-radio label="createdDate asc">发布时间升序 </el-radio>
                <el-radio label="updatedDate desc">修改时间降序</el-radio>
                <el-radio label="updatedDate asc">修改时间升序</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row class="edit-row"> -->
        <el-row>
          <el-col :span="24" style="height: 100%">
            <el-form-item label="编辑器" class="codeEditor">
              <EditorPlus
                v-bind:template.sync="ruleForm.template"
                ref="editorPlus"
              ></EditorPlus>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-row
      :gutter="10"
      class="grid-content btn_wrap_bottom"
      type="flex"
      justify="end"
    >
      <el-col :span="1.5" v-if="false">
        <el-button round @click="resetForm('ruleForm')">重置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button round @click="handleClose">取消</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          round
          @click="submitForm('ruleForm')"
          v-hasPermi="['system:article:add']"
          >确定</el-button
        >
      </el-col>
    </el-row>
  </div>
</template>

<script>
import CodeEditor from "@/components/codeEditor";
import pinyin from "js-pinyin";
import EditorPlus from "@/components/EditorPlus";
import { validHttp } from "@/utils/validate";
import {
  getChannelAppendDetails,
  addTemplate,
  editTemplate,
  repeatName,
} from "@/api/content/clounm";

export default {
  props: {},
  data() {
    var validateNameRepeat = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("模板名称不能为空"));
      }
      if (!this.templateId) {
        setTimeout(() => {
          repeatName({ name: value, channelId: this.channelId }).then((res) => {
            if (res.data) {
              return callback("文章名称已存在");
            } else {
              return callback();
            }
          });
        }, 300);
      } else {
        return callback();
      }
    };
    var validateCountPerRow = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("内容最大字数不能为空"));
      }
      // if (!Number.isInteger(value)) {
      //   callback(new Error("请输入数字值"));
      // } else {
      if (value < 1 || value > 9999) {
        callback(new Error("字数只能在1-9999之间"));
      } else {
        callback();
      }
      // }
    };
    var validatemaxHeader = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("标题最大长度不能为空"));
      }
      // if (!Number.isInteger(value)) {
      //   callback(new Error("请输入数字值"));
      // } else {
      if (value < 1 || value > 1000) {
        callback(new Error("字数只能在1-1000之间"));
      } else {
        callback();
      }
      // }
    };
    return {
      radio1: "code",
      radio: 1,
      ruleForm: {
        imgSize: "320,240",
        imgSize1: "320",
        imgSize2: "240",
        imgAlign: "0",
        articleForNew: 0,
        countPerRow: 30,
        articlePageHeight: 380,

        channelId: this.$route.query.channelId,
        createdDate: null,
        isAppend: 1, //是否是附加模板：1是|0否
        listOrder: "createdDate desc",
        maxHeader: 30,
        name: null,
        oneRowArticleNum: 1,
        state: 1,
        template: "",
        updatedDate: null,
        listId: null,
      },
      templateId: this.$route.query.templateId || null,
      channelId: this.$route.query.channelId || null,
      rules: {
        name: [
          {
            required: true,
            validator: validateNameRepeat,
            trigger: ["blur"],
          },
        ],
        countPerRow: [
          { required: true, validator: validateCountPerRow, trigger: "blur" },
        ],
        maxHeader: [{ validator: validatemaxHeader, trigger: "blur" }],
        articlePageHeight: [
          { required: false, message: "列表区高度不能为空" },
          { type: "number", message: "列表区高度必须为数字值" },
        ],
        articleForNew: [
          { required: false, message: "文章标新期限不能为空" },
          { type: "number", message: "文章标新期限必须为数字值" },
        ],
        oneRowArticleNum: [
          { required: false, message: "每行文章数目不能为空" },
          { type: "number", message: "每行文章数目必须为数字值" },
        ],
        oneRowArticleNum: [
          { required: false, message: "每行文章数目不能为空" },
          { type: "number", message: "每行文章数目必须为数字值" },
        ],
      },
    };
  },

  components: { CodeEditor, EditorPlus },

  computed: {},

  mounted() {
    if (this.templateId) this.getAppendArticleDetail();
    else {
      this.$nextTick(() => {
        this.$refs.editorPlus.radio1 = "view";
      });
    }
  },

  watch: {},

  methods: {
    async getAppendArticleDetail() {
      await getChannelAppendDetails(this.templateId).then((res) => {
        [res.data.imgSize1, res.data.imgSize2] = res.data.imgSize.split(",");
        this.ruleForm = res.data;
        // this.$refs.editorPlus.$refs.codeEditor.aceEditor.setValue(
        //   this.ruleForm.template
        // );
      });
      this.$nextTick(() => {
        this.$refs.editorPlus.radio1 = "view";
      });
    },
    submitForm(formName) {
      if (this.ruleForm.template == null) {
        alert("模板内容不能为空");
        return;
      }
      console.log(
        "🚀 ~ file: appendArticle.vue:278 ~ submitForm ~ this.ruleForm.template",
        this.ruleForm.template
      );
      if (validHttp(this.ruleForm.template)) {
        this.$confirm(
          "模板内容中包含IP地址，可能涉及IP泄露问题，确认继续操作吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: false,
          }
        )
          .then(() => {
            this.handleBaocun(formName);
          })
          .catch(() => {
            return;
          });
      } else {
        this.handleBaocun(formName);
      }
    },
    handleBaocun(formName) {
      this.ruleForm.imgSize =
        this.ruleForm.imgSize1 + "," + this.ruleForm.imgSize2;
      // this.ruleForm.template = this.ruleForm.template
      //   .replaceAll("<p>{", "{")
      //   .replaceAll("}</p>", "}")
      //   .replaceAll("}<br/></p>", "}<br>")
      //   .replaceAll("}<br></p>", "}<br>")
      //   .replaceAll("<p><br></p>", "<br>");
      this.$refs[formName].validateField("name", (errorMessage) => {
        if (!errorMessage) {
          //addAppendArticle
          //新增附加文章模板
          if (!this.templateId) {
            addTemplate(this.ruleForm).then((res) => {
              if (res.code == 200) {
                this.msgSuccess("添加成功");
                this.closeWindow();
              }
              // window.open("about:blank", "_top").close();
            });
          }
          //修改附加文章模板
          else {
            editTemplate(this.ruleForm).then((res) => {
              if (res.code == 200) {
                this.msgSuccess("修改成功");
                this.closeWindow();
              }
              // window.open("about:blank", "_top").close();
            });
          }
        } else {
          return false;
        }
      });
    },

    getTemplete(template) {
      // this.$emit('updat')
      // this.$emit("getCode", { tab: "one", template: template });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClose() {
      this.$confirm("此操作将不保存并关闭本页面，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.closeWindow();
        })
        .catch(() => {
          return;
        });
    },
    //文章名字是否存在
    nameRepeat() {},
  },
};
</script>

<style scoped lang="scss">
@import "~@/assets/styles/el-form.scss";

.four {
  width: 80%;
  min-width: 1200px;
  margin: 0 auto;
  height: 100%;

  padding-bottom: 86px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.title {
  height: 40px;
  line-height: 40px;
  color: #000;
  font-weight: bold;
  text-align: center;
  font-size: 20px;
}
.form-content {
  padding: 10px;
  background: #fff;
  flex: 1;
  overflow: hidden;
  .editor-plus-form {
    height: 100%;
    display: flex;
    flex-direction: column;
    .edit-row {
      flex: 1;
      overflow: hidden;
    }
  }
}

.btn_wrap_bottom {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1000;
  margin-bottom: 0;
  height: 64px;
  justify-content: center;
  border-top: 1px solid #e8e8e8;
}
// ::v-deep .codeEditor {
//   .el-form-item__content {
//     height: 500px;
//   }
// }
.codeEditor {
  height: 100%;
  ::v-deep .el-form-item__content {
    height: 100%;
  }
}
::v-deep .el-form-item__content {
  .el-input-group {
    vertical-align: unset;
    .el-input-group__append,
    .el-input-group__prepend {
      // background: transparent;
      // border: none;

      border: 1px solid #dcdfe6;
      border-radius: 0;
      padding: 0 4px;
    }
  }
}
</style>
<style>
/* #app {
  height: auto;
  min-height: 100% !important;
  overflow: inherit;
} */
</style>
